﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;

namespace CorpStoreServer
{
    class StartStoreApp
    {
        private Log log;

        /// <summary>
        /// This function attempts to start a store app.  If the app is not installed yet, 
        /// the user will be taken to the Windows Store to download.  Note that it is not
        /// possible at this time to install a store app directly.  The user must choose
        /// to install it from the Windows Store.
        /// 
        /// displayName=<display-name of store app>
        /// familyName=<package family name>
        /// storeID=<unique store ID to use when launching windows store if pkg not installed>
        /// </summary>
        /// <param name="parms"></param>
        public void Run(Log log, NameValueCollection parms)
        {
            try
            {
                string displayName = GenLib.GetParm(parms, "displayName");
                string familyName = GenLib.GetParm(parms, "familyName");
                string storeID = GenLib.GetParm(parms, "storeID");
                string packageIdentity;
                string version;
                string strErr;
                Package package;

                this.log = log;
                logInfo("Attempting to start store app with displayName '{0}', familyName '{1}', and storeID '{2}'...", displayName, familyName, storeID);
                if (!string.IsNullOrEmpty(familyName))
                    package = GenLib.FindPackageByFamilyName(familyName);
                else
                    package = GenLib.FindPackageByDisplayName(displayName);
                GenLib.GetPackageDetails(package, out packageIdentity, out version, out strErr);

                // check to see if package already exists on this machine
                if (package != null)
                {
                    logInfo("Found store application to be previously installed.  Attempting to activate it");
                    uint processID;
                    string id = package.Id.FamilyName + "!" + packageIdentity;

                    CorpStoreServer.ActivationManager.ApplicationActivationManager appActiveManager = new ActivationManager.ApplicationActivationManager();
                    appActiveManager.ActivateApplication(id, null, CorpStoreServer.ActivationManager.ActivateOptions.None, out processID);

                    if (processID == 0)
                        logErr("Error starting store app {0} - cannot start", displayName);
                    else
                        logInfo("Started store app {0} OK!", displayName);

                    System.Threading.Thread.Sleep(2000);
                }
                else
                {
                    // is a store app - take user to the store
                    logInfo("Store app '{0}' is not yet installed - taking user to app store", displayName);
                    string uri = "ms-windows-store:PDP?PFN=" + storeID;
                    Process p = Process.Start(uri);
                }
            }
            catch (Exception ex)
            {
                logErr("Unhandled exception in startStoreApp: {0}", ex.Message);
                if (ex.InnerException != null)
                    logErr("Inner Exception: {0}", ex.InnerException.Message);
            }
        }


        private void logInfo(string msg, params object[] parms)
        {
            if (log != null)
                log.LogInfo(msg, parms);
        }


        private void logErr(string msg, params object[] parms)
        {
            if (log != null)
                log.LogErr(msg, parms);
        }



    }
}
